package cc.ufinity.networkdiagnose.widget;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cc.ufinity.networkdiagnose.chart.ChartManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.PullTaskParser;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TaskParser;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;
import android.app.Activity;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.wifi.ScanResult;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class ApRelevanceTestWidget extends GeneralTestWidget {

    private WlanManager wlanManager;
    private Handler handler;
    private Activity ctx;
    private LinearLayout l;
    private ScrollView sv;
    private LinearLayout chartLayout;
    private static final String TAG = "ApRelevanceTest";
    private Button backBtn;
    private Button btnRetest;
    private boolean connecting;
    private int current;
    private int timeout_num;
    private int frequency = 4;
    private int totalTime;
    private double[] xdata;
    private double[] ydata;
    private Task task;
    private String fileName;

    public ApRelevanceTestWidget(Activity context) {
        super(context);
        inflate(context, R.layout.aprelevance_test_widget, this);
        this.ctx = context;
        l = (LinearLayout) this.findViewById(R.id.aprelev_test_layout);
        sv = (ScrollView) findViewById(R.id.ap_test_ScrView);
        chartLayout = (LinearLayout) findViewById(R.id.apTestChartLayout);
        backBtn = (Button) findViewById(R.id.ap_test_btnback);
        btnRetest = (Button) findViewById(R.id.btn_retest);
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                back(ctx);
            }
        });

        btnRetest.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // ApRelevanceTestWidget aw = new ApRelevanceTestWidget(ctx);
                // ctx.setContentView(aw);
                // aw.scanWifi();
                if (null != fileName) {
                    new UploadResultTask().execute();
                } else {
                    showMessage(ctx, "文件已上传或未进行测试.");
                }
            }
        });
        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.WIFI_RECEIVE_LIST:
                    dismissMessageDialog();
                    showWifiListDialog(ctx, wlanManager, handler);
                    wlanManager.stopScan();
                    break;
                case MessageWhat.WIFI_SELECTED:
                    start(selectedScanResult);
                    break;
                case MessageWhat.FTP_ACCOUNT_INVALID:
                    dismissMessageDialog();
                    showMessage(ctx, "无法获取FTP账号，请检查FTP配置.");
                    break;
                case MessageWhat.FTP_UPLOAD_TASK_DONE:
                    dismissMessageDialog();
                    showMessage(ctx, "上传成功.");
                    break;
                case MessageWhat.FTP_UPLOAD_FAILED:
                    dismissMessageDialog();
                    showMessage(ctx, "上传失败，请检查FTP配置是否正确.");
                    break;
                case MessageWhat.FTP_LOGIN_FAILED:
                    dismissMessageDialog();
                    showMessage(ctx, "FTP登录失败，请检查FTP配置是否正确.");
                    break;
                default:
                    update(msg.what);
                }
            }
        };
        wlanManager = new WlanManager(ctx);
        wlanManager.setHandler(handler);
        task = new Task();
    }

    protected void scanWifi() {
        showMessageDialog(ctx, "正在扫描附近Wifi热点...");
        new Thread() {
            public void run() {
                wlanManager.startScan();
            }
        }.start();
    }

    private final class ApTestThread extends Thread {
        private ScanResult scan;

        public ApTestThread(final ScanResult scan) {
            this.scan = scan;
        }

        @Override
        public void run() {
            while (current < frequency && executable) {
                if (!connecting) {
                    current++;
                    connecting = true;
                    wlanManager.connect(scan);
                    //startConnectTimeoutListener();
                }
            }
        }

    }

    private void start(final ScanResult scan) {
        final FTPConfig ftp = this.getFTPConfig(ctx);
        if (ftp != null) {
            xdata = new double[frequency];
            ydata = new double[frequency];
            final ApTestThread apTestThread = new ApTestThread(scan);
            this.showProgressDialog(ctx, "正在进行AP关联测试...", frequency);
            initTask(task, ctx, ConnectivityManager.TYPE_WIFI);
            task.startTime = StringUtils.getDateTime();
            apTestThread.start();
        }
    }

    private void startConnectTimeoutListener() {
        TimerTask wifiReceiverTask = new TimerTask() {
            public void run() {
                if (connecting) {
                    Log.e(TAG, "AP关联第" + current + "测试连接超时");
                    wlanManager.setConnectedConsumeTime(System.currentTimeMillis());
                    wlanManager.sendMsg(MessageWhat.WIFI_CONNECT_TIMEOUT);
                }
            }
        };
        Timer timer = new Timer();
        timer.schedule(wifiReceiverTask, WlanManager.CONNECT_TIMEOUT);
    }

    void update(int what) {
        setDialogProgress(current);
        switch (what) {
        case MessageWhat.WIFI_SUCESS_CONNECTED:
            if (connecting) {
                long costTime = (wlanManager.getConnectedConsumeTime() - wlanManager.getStartConntectTime()) / 1000;
                xdata[current - 1] = current;
                ydata[current - 1] = costTime;
                StringBuffer s = new StringBuffer();
                s.append("第").append(current).append("次关联AP点：");
                s.append(wlanManager.getCurrentScanResult().SSID).append(" MAC地址：");
                s.append(wlanManager.getCurrentScanResult().BSSID).append('\n');
                s.append("IP：").append(wlanManager.getIpAddress()).append(" 时间：");
                s.append(costTime).append(" s");
                totalTime += costTime;
                TextView tv = new TextView(ctx);
                tv.setTextSize(12);
                tv.setText(s);
                l.addView(tv);
                if (current == frequency) {
                    wlanManager.sendMsg(MessageWhat.DONE);
                }
                connecting = false;
            }
            break;
        case MessageWhat.WIFI_CONNECT_TIMEOUT:
            StringBuffer s = new StringBuffer();
            s.append("第").append(current).append("次关联 AP点：");
            s.append(wlanManager.getCurrentScanResult().SSID).append(" MAC地址：");
            s.append(wlanManager.getCurrentScanResult().BSSID).append("失败.");
            TextView tv = new TextView(ctx);
            tv.setTextSize(12);
            tv.setText(s);
            l.addView(tv);
            setTimeoutNum(1);
            
            if (current == frequency) {
                wlanManager.sendMsg(MessageWhat.DONE);
            }
            connecting = false;
            break;
        case MessageWhat.DONE:
            s = new StringBuffer();
            DecimalFormat df = new DecimalFormat("#0.000");
            int success = frequency - timeout_num;
            s.append("关联测试次数：").append(frequency);
            s.append(" 关联成功次数：").append(success).append('\n');
            s.append("关联成功率：").append((float) success / frequency * 100).append('%');
            s.append(" 关联平均时延：").append(df.format((float) (totalTime / frequency))).append('s');
            tv = new TextView(ctx);
            tv.setTextSize(13);
            tv.setTextColor(Color.CYAN);
            tv.setText(s);
            l.addView(tv);
            drawChart();
            
            task.endTime = StringUtils.getDateTime();
            task.relevanceAPAvgTime = df.format((float) (totalTime / frequency));
            task.relevanceAPSuccessRate = String.valueOf((float) success / frequency * 100);
            
            this.dismissProgressDialog();
            connecting = false;
            break;
        }
        setScrollViewDown(sv);

    }

    private void drawChart() {
        ChartManager cm = new ChartManager(ctx, 5, 50);
        String chartTitle = "AP关联测试";
        String[] lineTitles = new String[] { "AP关联时间" };
        List<double[]> x = new ArrayList<double[]>(1);
        List<double[]> y = new ArrayList<double[]>(1);
        x.add(xdata);
        y.add(ydata);
        int[] colors = new int[] { Color.GREEN };
        View lineChart = cm.createLineChart(colors, chartTitle, lineTitles, x, y);
        chartLayout.addView(lineChart);
        
        new UploadResultTask().execute();
    }

    private void setTimeoutNum(int timeout_num) {
        this.timeout_num += timeout_num;
    }
    
    private class UploadResultTask extends AsyncTask<Void, Void, String> {
        protected void onPreExecute() {
            showMessage(ctx, "正在上传结果...");
        }

        @Override
        protected String doInBackground(Void... params) {
            
            if (fileName == null) {
                TaskParser parser = new PullTaskParser();
                fileName = parser.XmlFileCreator(task);
            }
            if (uplod(fileName, ctx, handler)) {
                fileName = null;
            }
            return fileName;
        }
/*
        protected void onPostExecute(String result) {
            if (result == null) {
                showMessage(ctx, "上传成功.");
            }
        }*/
    }
}
